package com.gzkemays.server1.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.Principal;

@Controller("service1")
public class Service1Controller {
  @RequestMapping(
      path = {"/", "/home"},
      method = RequestMethod.GET)
  public String home() {
    return "home";
  }

  @PreAuthorize("hasRole('USER')")
  @RequestMapping(path = "/user", method = RequestMethod.GET)
  public ModelAndView user() {
    return new ModelAndView("user");
  }

  @PreAuthorize("hasRole('ADMIN')")
  @RequestMapping(path = "/admin", method = RequestMethod.GET)
  public ModelAndView admin() {
    return new ModelAndView("admin");
  }

  @GetMapping("/logout")
  @ResponseBody
  public String logout(   HttpServletRequest httpServletRequest,
                               HttpServletResponse httpServletResponse) {
    Cookie[] cookies = httpServletRequest.getCookies();
    if (cookies != null && cookies.length > 0) {
      for (Cookie cookie : cookies) {
        cookie.setMaxAge(0);
        cookie.setPath("/");
        httpServletResponse.addCookie(cookie);
      }
    }
    return "登出";
  }
  /**
   * 测试 /api/* 是否被资源服务器拦截，需要token
   *
   * @return
   */
  @GetMapping("/api/getUserInfo")
  @ResponseBody
  public Principal getUserInfo() {
    return SecurityContextHolder.getContext().getAuthentication();
  }

  @GetMapping("/api2/getUserInfo")
  @ResponseBody
  public Principal getUserInfo2() {
    return SecurityContextHolder.getContext().getAuthentication();
  }
}
